package com.yunqian.web;

import com.yunqian.common.JSONResult;
import com.yunqian.util.validate.Validator;
import org.springframework.core.MethodParameter;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Created by zou on 2018/6/4
 */
public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler delegate;

    public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate) {
        this.delegate = delegate;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return delegate.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        String url = "";
        if(webRequest.getNativeRequest() instanceof SecurityContextHolderAwareRequestWrapper){
            SecurityContextHolderAwareRequestWrapper wrapper = (SecurityContextHolderAwareRequestWrapper) webRequest.getNativeRequest();
            url = wrapper.getRequestURI();
        }
        if(Validator.equals(url, "/api/zpt/notify")){
            // 如果匹配上了众票通的核销回调地址则直接返回
            delegate.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
        }else {
            JSONResult result = new JSONResult(returnValue);
            delegate.handleReturnValue(result, returnType, mavContainer, webRequest);
        }
    }
}